/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

package com.xinyue.server.framework.server.websocket;

import com.google.common.util.concurrent.RateLimiter;
import com.xinyue.server.framework.common.GameFrameworkConfig;
import com.xinyue.server.framework.handler.GameChannelConfirmHandler;
import com.xinyue.server.framework.handler.GameRequestDispatcherHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.context.ApplicationContext;

/**
 * web socket channel实始化器，用于创建支持web socket连接的游戏服务
 *
 * @author 王广帅
 * @since 2021/1/24 17:20
 */
public class WebSocketServerChannelInitializer extends ChannelInitializer<Channel> {

    private ApplicationContext context;
    /**
     * 全局请求QPS限制器
     */
    private RateLimiter globalLimiter;

    /**
     * 构造方法
     *
     * @param context spring 容器
     */
    public WebSocketServerChannelInitializer(ApplicationContext context) {
        this.context = context;
        GameFrameworkConfig gameFrameworkConfig = context.getBean(GameFrameworkConfig.class);
        globalLimiter = RateLimiter.create(gameFrameworkConfig.getGlobalRequestQps());
    }

    /**
     * 初始化一个netty channel信息
     *
     * @param ch 当前创建的channel
     */
    @Override
    protected void initChannel(Channel ch) {
        GameFrameworkConfig gameServerConfig = context.getBean(GameFrameworkConfig.class);
        ch.pipeline().addLast(new HttpServerCodec());
        ch.pipeline().addLast(new ChunkedWriteHandler());
        ch.pipeline().addLast(new HttpObjectAggregator(1024 * 1024 * 5));
        ch.pipeline().addLast(new WebSocketServerProtocolHandler("/request"));
        // 创建QPS限制器
        RateLimiter singleLimiter = RateLimiter.create(gameServerConfig.getRequestQps());
        //  ch.pipeline().addLast(new RequestFilterHandler(globalLimiter, singleLimiter));
        ch.pipeline().addLast(new WebSocketDecoderHandler());
        ch.pipeline().addLast(new WebSocketEncoderHandler());
        // 添加连接通道确认handler
        GameChannelConfirmHandler channelConfirmHandler = context.getBean(GameChannelConfirmHandler.class);
        ch.pipeline().addLast(channelConfirmHandler);
        GameRequestDispatcherHandler requestDispatcherHandler = context.getBean(GameRequestDispatcherHandler.class);
        ch.pipeline().addLast(requestDispatcherHandler);
    }
}
